package com.cn.chaomeng.utils;

import com.cn.chaomeng.model.Food;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author LYJ
 *         Created by Administrator on 2018/2/28 0028.
 */
public class MultipartFileUtil {

    public final static String FOOD_IMAGE_PATH = "img/food/";

    public final static String FOOD_TYPE_IMAGE_PATH = "img/foodtype";

    private final static String ROOT_PATH = ContextLoader.getCurrentWebApplicationContext().getServletContext().getRealPath("/") + "static/";

    public static String setImage(String type, MultipartFile imgFile){
        String result = null;
        try {
            if(imgFile != null){
                //获取文件原始名称
                String originalFilename = imgFile.getOriginalFilename();
                //上传图片
                if(originalFilename!=null && originalFilename.length()>0){
                    //存储图片的物理路径
                    String picPath = ROOT_PATH + type;
                    //新的图片名称
                    String newFileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
                    //新图片
                    File newFile = new File(picPath+newFileName);
                    //将内存中的数据写入磁盘
                    imgFile.transferTo(newFile);
                    result = type + newFileName;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return result;
    }

    public static boolean deleteImage(String url) {
        if(url != null){
            File file = new File(ROOT_PATH + url);
            return file.isFile() && file.delete();
        }
        return false;
    }
}
